package com.bdk.middle.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdk.middle.management.api.domain.RoleDO2;
import com.bdk.middle.management.api.query.PermissionAssignQueryDO;
import com.bdk.middle.management.core.entity.*;
import com.bdk.middle.management.core.mapper.AdminMapper;
import com.bdk.middle.management.core.mapper.AdminRoleMapper;
import com.bdk.middle.management.core.mapper.RoleMapper;
import com.bdk.middle.management.api.domain.RoleDO;
import com.bdk.middle.management.api.query.RoleQueryDO;
import com.bdk.middle.common.status.ErrorCode;
import com.bdk.middle.common.domain.PageDO;
import com.bdk.middle.common.result.ResultDO;
import com.bdk.middle.common.util.BeanUtilsExtends;
import com.bdk.middle.common.util.Constant;
import com.bdk.middle.management.core.mapper.RolePermissionMapper;
import com.bdk.middle.management.service.AdminService;
import com.bdk.middle.management.service.PermissionService;
import com.bdk.middle.management.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author Reagan
 * @since 2021-01-23
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleEntity> implements RoleService {

    private Logger          logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private RoleMapper        roleMapper;

    @Autowired
    private RolePermissionMapper   rolePermissionMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private AdminMapper adminMapper;


    @Override
    public ResultDO add(RoleDO domain) {

        RoleEntity entity = new RoleEntity();
        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        entity.setCreateDate(Calendar.getInstance().getTime());
        entity.setModifiDate(entity.getCreateDate());
        entity.setModifier(entity.getCreator());

        int res = -1;
        try {
            res = roleMapper.insert(entity);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ROLE_ADD_ERROR);
            logger.debug("error code：" + ErrorCode.ROLE_ADD_ERROR.getCode() + " msg" + ErrorCode.ROLE_ADD_ERROR.getMsg());
            return result;
        }
        if(domain.getPermissionIds()!=null){
            //传递权限才绑定,没有则不绑定
            result = permissionService.bindPermissions(entity.getId(), domain.getPermissionIds());
        }

        return result;
    }

    public ResultDO bindRoles(String userId, List<String> roleIds) {

        ResultDO result = new ResultDO();

        for(String roleId : roleIds) {
            AdminRoleEntity entity = new AdminRoleEntity();
            entity.setUserId(userId);
            entity.setRoleId(roleId);
            int res = -1;
            try {
                res = adminRoleMapper.insert(entity);
            } catch (Exception e) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                return result;
            }

            //判断r的值是否小于0.如果小于0 就代表添加失败
            if(res < 0) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.ROLE_BIND_USER_ERROR);
                logger.debug("error code：" + ErrorCode.ROLE_BIND_USER_ERROR.getCode() + " msg" + ErrorCode.ROLE_BIND_USER_ERROR.getMsg());
                return result;
            }
        }
        return result;
    }

    public ResultDO unbindRoles(String userId) {

        ResultDO result = new ResultDO();

        int res = -1;
        try {
            res = adminRoleMapper.delete(Wrappers.<AdminRoleEntity>lambdaQuery().eq(AdminRoleEntity::getUserId, userId));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ROLE_UNBIND_USER_ERROR);
            logger.debug("error code：" + ErrorCode.ROLE_UNBIND_USER_ERROR.getCode() + " msg" + ErrorCode.ROLE_UNBIND_USER_ERROR.getMsg());
            return result;
        }

        return result;
    }

    /**
     * 获取系统用户角色
     */
    public ResultDO getRoleByUserId2(String userId) {
        ResultDO result = new ResultDO();
        List<AdminRoleEntity> list = null;
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id",userId);
        //查用户角色关联表
        try {
            list = adminRoleMapper.selectList(wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        if(list.size() == 0) {
            return result;
        }
        //查角色表
        List<String> roleIds = new ArrayList<>();

        for(AdminRoleEntity entity : list) {
            roleIds.add(entity.getRoleId());
        }

        List<RoleEntity> list2 = null;
        try {
            list2 = roleMapper.selectBatchIds(roleIds);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<RoleDO> doList = getDomainList(list2);

        if(doList == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ROLE_LIST_ERROR);
            logger.debug("error code：" + ErrorCode.ROLE_LIST_ERROR.getCode() + " msg" + ErrorCode.ROLE_LIST_ERROR.getMsg());
            return result;
        }
        result.setModel(ResultDO.FIRST_MODEL_KEY, doList);
        return result;
    }

    public ResultDO getRoleByUserId(String userId) {

        ResultDO result = new ResultDO();

        List<AdminRoleEntity> list = null;
        try {
            list = adminRoleMapper.selectList(Wrappers.<AdminRoleEntity>lambdaQuery().eq(AdminRoleEntity::getUserId, userId));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        if(list.size() == 0) {
            return result;
        }
        List<String> roleIds = new ArrayList<>();

        for(AdminRoleEntity entity : list) {
            roleIds.add(entity.getRoleId());
        }

        List<RoleEntity> list2 = null;
        try {
            list2 = roleMapper.selectBatchIds(roleIds);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<RoleDO> doList = getDomainList(list2);

        if(doList == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ROLE_LIST_ERROR);
            logger.debug("error code：" + ErrorCode.ROLE_LIST_ERROR.getCode() + " msg" + ErrorCode.ROLE_LIST_ERROR.getMsg());
            return result;
        }
        result.setModel(ResultDO.FIRST_MODEL_KEY, doList);
        return result;
    }


    @Override
    public ResultDO edit(RoleDO domain) {

        RoleEntity entity = new RoleEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        entity.setModifiDate(Calendar.getInstance().getTime());

        int res = -1;
        try {
            res = roleMapper.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ROLE_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.ROLE_EDIT_ERROR.getCode() + " msg" + ErrorCode.ROLE_EDIT_ERROR.getMsg());
            return result;
        }

        if(domain.getPermissionIds() != null) {
            result = permissionService.unbindPermissions(domain.getId());
            if(!result.isSuccess()) {
                logger.debug(result.getErrorCode().getMsg());
                return result;
            }
            result = permissionService.bindPermissions(domain.getId(), domain.getPermissionIds());
            if(!result.isSuccess()) {
                logger.debug(result.getErrorCode().getMsg());
                return result;
            }
        }

        return result;
    }



    @Override
    public ResultDO get(String id) {

        ResultDO result = new ResultDO();

        RoleEntity entity = null;

        try {
            entity = roleMapper.selectById(id);
        } catch(Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        RoleDO domain = getDomain(entity);

        if(domain == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ROLE_GET_ERROR);
            logger.debug("error code：" + ErrorCode.ROLE_GET_ERROR.getCode() + " msg" + ErrorCode.ROLE_GET_ERROR.getMsg());
            return result;
        }

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }

    @Override
    public ResultDO remove(String id, String modifier) {

        ResultDO result = new ResultDO();

        RoleEntity entity = new RoleEntity();

        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);
        entity.setId(id);
        entity.setIsDelete(Constant.IS_DELETE);

        int res = -1;
        try {
            res = roleMapper.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ROLE_DELETE_ERROR);
            logger.debug("error code：" + ErrorCode.ROLE_DELETE_ERROR.getCode() + " msg" + ErrorCode.ROLE_DELETE_ERROR.getMsg());
            return result;
        }

        return result;
    }


    @Override
    public ResultDO find(RoleQueryDO query) {

        RoleEntity entity = new RoleEntity();

        ResultDO result = BeanUtilsExtends.copy(entity,query);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        QueryWrapper<RoleEntity> wrapper = new QueryWrapper<RoleEntity>(entity);

        Page<RoleEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());
        IPage<RoleEntity> iPage = null;
        try {
            iPage = roleMapper.selectPage(page, wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<RoleDO> doList = getDomainList(iPage.getRecords());

        if(doList == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ROLE_LIST_ERROR);
            logger.debug("error code：" + ErrorCode.ROLE_LIST_ERROR.getCode() + " msg" + ErrorCode.ROLE_LIST_ERROR.getMsg());
            return result;
        }

        PageDO<RoleDO> pageDO = new PageDO<>();
        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
        return result;
    }

    private RoleDO getDomain(RoleEntity entity) {
        ResultDO result = new ResultDO();
        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if(entity == null) return null;
        RoleDO domain = new RoleDO();

        if(!result.isSuccess()) {
            return null;
        }
        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }


    private  List<RoleDO> getDomainList(List<RoleEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<RoleDO> doList = new ArrayList<>();

        //判断传入的list的集合的size是否大于0
        if(list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for(RoleEntity entity : list) {

                RoleDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if(domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }

    /**
     * 获取系统用户角色字符串集
     * @author chang
     *
     * @param sysUserName 系统用户名
     * @return
     */
    @Override
    public ResultDO getRolesByUsername(String sysUserName){
        ResultDO result = new ResultDO();
        Set<String> roleSet = new HashSet<>();

        //查用户id
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username",sysUserName);
        wrapper.eq("is_delete",Constant.IS_DELETE_FALSE);
        AdminEntity sysUserRecord =adminMapper.selectOne(wrapper);
        if(sysUserRecord==null){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.USER_GET_ERROR);
            logger.debug("error code：" + ErrorCode.USER_GET_ERROR.getCode() + " msg" + ErrorCode.USER_GET_ERROR.getMsg());
            return result;
        }
        //查角色
        QueryWrapper wrapper2 = new QueryWrapper();
        wrapper2.eq("user_id",sysUserRecord.getId());
        List<AdminRoleEntity> adminRoleRecords =adminRoleMapper.selectList(wrapper2);

        //查找角色字符串，组装
        for(AdminRoleEntity adminRoleRecord:adminRoleRecords){
            QueryWrapper wrapper3 = new QueryWrapper();
            wrapper3.select("code");
            wrapper3.eq("id",adminRoleRecord.getRoleId());
            RoleEntity roleRecord =roleMapper.selectOne(wrapper3);
            if(roleRecord!=null){
                roleSet.add(roleRecord.getCode());
            }

        }
        result.setModel(ResultDO.FIRST_MODEL_KEY, roleSet);

        return result;
    }


    /**
     * 获取系统用户角色id集
     * @author chang
     *
     * @param sysUserName 系统用户名
     * @return
     */
    @Override
    public ResultDO getRoleIdsByUsername(String sysUserName){
        ResultDO result = new ResultDO();
        Set<String> roleIDSet = new HashSet<>();

        //查用户id
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username",sysUserName);
        wrapper.eq("is_delete",Constant.IS_DELETE_FALSE);
        AdminEntity sysUserRecord =adminMapper.selectOne(wrapper);
        if(sysUserRecord==null){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.USER_GET_ERROR);
            logger.debug("error code：" + ErrorCode.USER_GET_ERROR.getCode() + " msg" + ErrorCode.USER_GET_ERROR.getMsg());
            return result;
        }
        //查角色
        QueryWrapper wrapper2 = new QueryWrapper();
        wrapper2.eq("user_id",sysUserRecord.getId());
        List<AdminRoleEntity> adminRoleRecords =adminRoleMapper.selectList(wrapper2);

        //查找角色字符串，组装
        for(AdminRoleEntity adminRoleRecord:adminRoleRecords){
            roleIDSet.add(adminRoleRecord.getRoleId());
        }
        result.setModel(ResultDO.FIRST_MODEL_KEY, roleIDSet);

        return result;
    }


    /**
     * 分配单个权限给角色
     * @author chang
     *
     * @param domain
     * @return
     */
    @Override
    public ResultDO assignPermission(PermissionAssignQueryDO domain) {
        ResultDO result = new ResultDO();
        //参数校验
        if(domain.getPermissionId()==null || domain.getRoleId()==null){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.REQUEST_PARAM_ERROR);
            logger.debug("error code：" + ErrorCode.REQUEST_PARAM_ERROR.getCode() + " msg" + ErrorCode.REQUEST_PARAM_ERROR.getMsg());
            return result;
        }
        //角色分配了该权限不能再分配
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("role_id",domain.getRoleId());
        wrapper.eq("permission_id",domain.getPermissionId());
        RolePermissionEntity record=rolePermissionMapper.selectOne(wrapper);
        if(record!=null){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ROLE_ALREADY_OWN_THIS_PERMISSION);
            logger.debug("error code：" + ErrorCode.ROLE_ALREADY_OWN_THIS_PERMISSION.getCode() + " msg" + ErrorCode.ROLE_ALREADY_OWN_THIS_PERMISSION.getMsg());
            return result;
        }
        //插入表
        RolePermissionEntity data=new RolePermissionEntity();
        data.setRoleId(domain.getRoleId());
        data.setPermissionId(domain.getPermissionId());
        rolePermissionMapper.insert(data);
        return result;
    }

    /**
     * 分配多个权限给角色
     * @author chang
     *
     * @param domain
     * @return
     */
    @Override
    @Transactional
    public ResultDO assignMultiPermission(PermissionAssignQueryDO domain) {
        ResultDO result = new ResultDO();
        //参数校验
        if(domain.getPermissionId()==null || domain.getRoleId()==null){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.REQUEST_PARAM_ERROR);
            logger.debug("error code：" + ErrorCode.REQUEST_PARAM_ERROR.getCode() + " msg" + ErrorCode.REQUEST_PARAM_ERROR.getMsg());
            return result;
        }
        String roleId=domain.getRoleId();
        String permissionIds=domain.getPermissionId();
        String [] permissionArr=permissionIds.split(",");
        if(permissionArr.length==0){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.REQUEST_PARAM_ERROR);
            logger.debug("error code：" + ErrorCode.REQUEST_PARAM_ERROR.getCode() + " msg" + ErrorCode.REQUEST_PARAM_ERROR.getMsg());
            return result;
        }
        //先删除该角色的权限分配
        QueryWrapper deleteWrapper = new QueryWrapper();
        deleteWrapper.eq("role_id",roleId);
        rolePermissionMapper.delete(deleteWrapper);

        //角色分配
        for(String permission:permissionArr){
            RolePermissionEntity data=new RolePermissionEntity();
            data.setRoleId(roleId);
            data.setPermissionId(permission);
            rolePermissionMapper.insert(data);
        }
        return result;
    }

    /**
     * 获取所有角色
     */
    @Override
    public ResultDO getAllRole() {
        ResultDO result = new ResultDO();

        QueryWrapper wrapper = new QueryWrapper();

        List<RoleEntity> list2 = null;
        List<RoleDO2> returnRoles = new ArrayList<>();
        try {
            wrapper.eq("is_delete",1);
            list2 = roleMapper.selectList(wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        for(RoleEntity item:list2){
            RoleDO2 tmpRole=new RoleDO2();
            tmpRole.setId(item.getId());
            tmpRole.setCode(item.getCode());
            tmpRole.setName(item.getName());
            tmpRole.setStatus(item.getStatus());
            returnRoles.add(tmpRole);
        }


        result.setModel(ResultDO.FIRST_MODEL_KEY, returnRoles);
        return result;
    }

    /**
     * 获取用户相关角色列表
     */
    @Override
    public ResultDO getRoleListByUsername(String username) {
        ResultDO result = new ResultDO();
        //查用户id
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("is_delete",1);
        wrapper.eq("username",username);
        AdminEntity adminRecord=adminMapper.selectOne(wrapper);
        if(adminRecord==null){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.USER_GET_ERROR);
            logger.debug("error code：" + ErrorCode.USER_GET_ERROR.getCode() + " msg" + ErrorCode.USER_GET_ERROR.getMsg());
            return result;
        }
        String userId=adminRecord.getId();
        //查用户角色
        QueryWrapper wrapper2 = new QueryWrapper();
        List<String>  roleIds=new ArrayList<>();
        List<AdminRoleEntity> adminRoleEntities=adminRoleMapper.selectList(wrapper2);
        for(AdminRoleEntity adminRole:adminRoleEntities){
              roleIds.add(adminRole.getRoleId());
        }
        if(roleIds.isEmpty()){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ROLE_GET_ERROR);
            logger.debug("error code：" + ErrorCode.ROLE_GET_ERROR.getCode() + " msg" + ErrorCode.ROLE_GET_ERROR.getMsg());
            return result;
        }
        //
        QueryWrapper wrapper3= new QueryWrapper();

        List<RoleEntity> list2 = null;
        List<RoleDO2> returnRoles = new ArrayList<>();
        try {
            wrapper3.eq("is_delete",1);
            wrapper3.in("id",roleIds);
            list2 = roleMapper.selectList(wrapper3);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ROLE_GET_ERROR);
            logger.debug("error code：" + ErrorCode.ROLE_GET_ERROR.getCode() + " msg" + ErrorCode.ROLE_GET_ERROR.getMsg());
            return result;
        }

        for(RoleEntity item:list2){
            RoleDO2 tmpRole=new RoleDO2();
            tmpRole.setId(item.getId());
            tmpRole.setCode(item.getCode());
            tmpRole.setName(item.getName());
            tmpRole.setStatus(item.getStatus());
            returnRoles.add(tmpRole);
        }

        result.setModel(ResultDO.FIRST_MODEL_KEY, returnRoles);
        return result;
    }

    /**
     * 根据用户id得到用户角色code字符串,code之间通过逗号分隔
     * 如果没有相关角色，则返回为null
     * @author chang
     *
     * @param sysUserId 系统用户名
     * @return
     */
    @Override
    public String getRoleStringByUserId(String sysUserId){
        String resultStr=null;
        Set<String> roleSet = new HashSet<>();

        //查角色
        QueryWrapper wrapper2 = new QueryWrapper();
        wrapper2.eq("user_id",sysUserId);
        List<AdminRoleEntity> adminRoleRecords =adminRoleMapper.selectList(wrapper2);

        //查找角色字符串，组装
        for(AdminRoleEntity adminRoleRecord:adminRoleRecords){
            QueryWrapper wrapper3 = new QueryWrapper();
            wrapper3.select("code");
            wrapper3.eq("id",adminRoleRecord.getRoleId());
            RoleEntity roleRecord =roleMapper.selectOne(wrapper3);
            if(roleRecord!=null){
                roleSet.add(roleRecord.getCode());
            }

        }
        if(!roleSet.isEmpty()){
            resultStr=org.apache.commons.lang3.StringUtils.join(roleSet.toArray(), ",");
        }


        return resultStr;
    }

    /**
     * 根据用户id得到用户角色名 name字符串,name之间通过逗号分隔
     * 如果没有相关角色，则返回为null
     * @author chang
     *
     * @param sysUserId 系统用户名
     * @return
     */
    @Override
    public String getRoleNamesByUserId(String sysUserId){
        String resultStr=null;
        Set<String> roleSet = new HashSet<>();

        //查角色
        QueryWrapper wrapper2 = new QueryWrapper();
        wrapper2.eq("user_id",sysUserId);
        List<AdminRoleEntity> adminRoleRecords =adminRoleMapper.selectList(wrapper2);

        //查找角色字符串，组装
        for(AdminRoleEntity adminRoleRecord:adminRoleRecords){
            QueryWrapper wrapper3 = new QueryWrapper();
            wrapper3.select("name");
            wrapper3.eq("id",adminRoleRecord.getRoleId());
            RoleEntity roleRecord =roleMapper.selectOne(wrapper3);
            if(roleRecord!=null){
                roleSet.add(roleRecord.getName());
            }

        }
        if(!roleSet.isEmpty()){
            resultStr = org.apache.commons.lang3.StringUtils.join(roleSet.toArray(), ",");
        }
        return resultStr;
    }

    /**
     * 根据用户id得到用户角色id
     * 单角色接口
     * 如果没有相关角色，则返回为null
     * @author chang
     *
     * @param sysUserId 系统用户名
     * @return
     */
    @Override
    public String getRoleIdByUserId(String sysUserId){

        //查角色
        QueryWrapper wrapper2 = new QueryWrapper();
        wrapper2.eq("user_id",sysUserId);
        List<AdminRoleEntity> adminRoleRecords =adminRoleMapper.selectList(wrapper2);

        //用户还没有分配角色
        if(adminRoleRecords==null || adminRoleRecords.isEmpty()){
            return null;
        }

        return adminRoleRecords.get(0).getRoleId();
    }

    /**
     * 根据角色code返回角色实体对象
     * 如果没有相关角色，则返回为null
     * @author chang
     *
     * @param code 角色code
     * @return
     */
    @Override
    public RoleEntity getRoleByCode(String code){
        //查角色
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("code",code);
        RoleEntity role=roleMapper.selectOne(wrapper);

        return role;
    }
}
